//
//  LXDownloadViewController.m
//  cat
//
//  Created by imera on 16/3/26.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXDownloadViewController.h"
#import "LXNavBarView.h"
#import "LXDownloadTableViewCell.h"
#import "MoviePlayerViewController.h"
#import "UIImage+Lx.h"
#import "MBProgressHUD+MJ.h"
#import "AFNetworking.h"

@interface LXDownloadViewController () <LXNavBarViewDelegate, UITableViewDataSource, UITableViewDelegate>

/**  本地缓存视频信息 */
@property (nonatomic, strong) NSMutableArray *downloadVideoArr;

@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) NSTimer *timer;

/** 是否为编辑模式 */
@property (nonatomic, assign) BOOL isEdit;

/** 删除按钮 */
@property (nonatomic, weak) UIButton *deleteBtn;

/** 自定义导航栏 */
@property (nonatomic, weak) LXNavBarView *navBarView;

/** 选中缓存视频数组 */
@property (nonatomic, strong) NSMutableArray *selectedVideoArr;
@end

@implementation LXDownloadViewController

- (NSMutableArray *)selectedVideoArr
{
    if (_selectedVideoArr == nil) {
        _selectedVideoArr = [NSMutableArray array];
    }
    return _selectedVideoArr;
}

/** 本地缓存视频信息懒加载 */
- (NSArray *)downloadVideoArr
{
    if (_downloadVideoArr == nil) {
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [path stringByAppendingPathComponent:@"downloadVideo.plist"];
        _downloadVideoArr = [NSMutableArray arrayWithContentsOfFile:filePath];

    }
    return _downloadVideoArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = MainBackgroundColor;
    self.isEdit = NO;
    [self initSubViews];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action) userInfo:nil repeats:YES];
    self.timer = timer;
}

#pragma mark - 计时器刷新缓存进度
- (void)action
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"downloadVideo.plist"];
    self.downloadVideoArr = [NSMutableArray arrayWithContentsOfFile:filePath];
    
    [self.tableView reloadData];
   
    BOOL timerStop = YES;

    for (int i=0;i<self.downloadVideoArr.count;i++) {
        NSDictionary *dict = self.downloadVideoArr[i];
        if (![dict[@"videoProgress"] isEqualToString:@"1.000"]) {
            timerStop = NO;
        }
    }
    
    if (timerStop) {
        [self.timer invalidate];
    }
}

#pragma mark - 初始化子控件
- (void)initSubViews
{
    /** 导航条 */
    LXNavBarView *navBarView = [[LXNavBarView alloc]init];
    navBarView.leftTitle = @"缓存记录";
    navBarView.rightTitle = @"编辑";
    navBarView.myDelegate = self;
    navBarView.frame = CGRectMake(0, 20, self.view.frame.size.width, LXNavBarHeight);
    [self.view addSubview:navBarView];
    self.navBarView = navBarView;
    
    if (self.downloadVideoArr == nil) {
        UILabel *label = [[UILabel alloc]init];
        label.text = @"暂无缓存的视频";
        label.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:label];

        CGFloat labelW = 200;
        CGFloat labelH = 50;
        CGFloat labelX = (self.view.frame.size.width - labelW) / 2;
        CGFloat labelY = (self.view.frame.size.height - labelH) / 2;
        label.frame = CGRectMake(labelX, labelY, labelW, labelH);
        
        self.navBarView.rightBtn.enabled = NO;
    }else{
        /** tableView视图 */
        UITableView *tableView = [[UITableView alloc]init];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.delegate = self;
        tableView.dataSource = self;
        self.tableView = tableView;
        [self.view addSubview:tableView];
        
        CGFloat tableViewX = 0;
        CGFloat tableViewY = 20 + LXNavBarHeight;
        CGFloat tableViewW = self.view.frame.size.width;
        CGFloat tableViewH = self.view.frame.size.height - tableViewY;
        tableView.frame = CGRectMake(tableViewX, tableViewY, tableViewW, tableViewH);
        
        /** 删除按钮 */
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
        [btn setTitle:@"删除" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor redColor]];
        [btn addTarget:self action:@selector(deleteVideo) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        self.deleteBtn  =btn;
        
        CGFloat btnW = self.view.frame.size.width;
        CGFloat btnH = 40;
        CGFloat btnX = 0;
        btn.frame = CGRectMake(btnX, self.view.frame.size.height, btnW, btnH);
        
        self.navBarView.rightBtn.enabled = YES;
    }
}

#pragma mark - tableView的代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.downloadVideoArr.count;
}

- (LXDownloadTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"Cell";
    
    LXDownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[LXDownloadTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.dict = self.downloadVideoArr[indexPath.row];

    /** 是否为编辑模式 */
    cell.isEdit = self.isEdit;
    
    if ([self.selectedVideoArr containsObject:@(indexPath.row)]) {
        cell.isSelected = YES;
    }else{
        cell.isSelected = NO;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isEdit) { //编辑模式
        LXDownloadTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.isSelected = !cell.isSelected;
        
        if ([self.selectedVideoArr containsObject:@(indexPath.row)]) {
            [self.selectedVideoArr removeObject:@(indexPath.row)];
        }else{
            [self.selectedVideoArr addObject:@(indexPath.row)];
        }

    }else{
        MoviePlayerViewController *moviePlayer = [[MoviePlayerViewController alloc]init];
        NSDictionary *dict = self.downloadVideoArr[indexPath.row];
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp4", path , dict[@"videoName"]];
        moviePlayer.filePath = filePath;
        
        [self.navigationController presentViewController:moviePlayer animated:YES completion:nil];
    }
}

- (void)dealloc
{
    self.timer = nil;
}

#pragma mark - 自定义导航栏视图
- (void)popCurrentViewController:(LXNavBarView *)navBarView
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightBtnClicked:(LXNavBarView *)navBarView
{
    UIButton *deleteBtn = self.deleteBtn;
    if (self.isEdit) { // 退出编辑模式
        [UIView animateWithDuration:0.5 animations:^{
            CGRect frame = self.deleteBtn.frame;
            frame.origin.y = self.view.frame.size.height;
            deleteBtn.frame = frame;
        }];
        self.navBarView.rightTitle = @"编辑";
    }else{ //进入编辑模式
        [UIView animateWithDuration:0.5 animations:^{
            CGRect frame = self.deleteBtn.frame;
            frame.origin.y = self.view.frame.size.height - frame.size.height;
            deleteBtn.frame = frame;
        }];
        self.navBarView.rightTitle = @"退出编辑";
    }
    
    self.isEdit = !self.isEdit;
    [self.tableView reloadData];
}

#pragma mark - 删除缓存视频
- (void)deleteVideo
{
    if (self.selectedVideoArr.count == 0) {
        [MBProgressHUD showError:@"请选择删除的视频"];
    }else{
        //删除缓存的视频
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSMutableIndexSet *indexSetes = [[NSMutableIndexSet alloc]init];
        for (int i=0; i<self.selectedVideoArr.count; i++) {
            NSNumber *num = self.selectedVideoArr[i];
            NSDictionary *dict = self.downloadVideoArr[[num integerValue]];
            NSString *videoName = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",dict[@"videoName"]]];
            NSString *videoPicture = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",dict[@"videoPicture"]]];
            
            if ([fileMgr fileExistsAtPath:videoName]) { //删除视频
                [fileMgr removeItemAtPath:videoName error:nil];
            }
            
            if ([fileMgr fileExistsAtPath:videoPicture]) { //删除视频图片
                [fileMgr removeItemAtPath:videoPicture error:nil];
            }
            
            [indexSetes addIndex:[num integerValue]];
        }
        //删除数组
        [self.downloadVideoArr removeObjectsAtIndexes:indexSetes];
        
        //保存缓存数据
        NSString *filePath = [path stringByAppendingPathComponent:@"downloadVideo.plist"];
        [self.downloadVideoArr writeToFile:filePath atomically:YES];
        
        //刷新表格
        [self.tableView reloadData];
        [MBProgressHUD showSuccess:@"删除视频成功"];
        
        self.selectedVideoArr = nil;
    }
}

@end
